package car.Postal.Grimentz;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.URISyntaxException;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;


import android.content.Context;
import android.util.Log;

public class StoppableDownloadThread extends Thread 
{
	public static final String TAG = "ZAGAZ";

	private String mURL;
//
	private HttpGet mMethod = null;
	private MapActivityHandler mHandler;
	Context c=null;
	HttpClient client = null;
	
	/**
	 * Volatile stop flag used to coordinate state between the two threads
	 * involved in this example.
	 */
	protected volatile boolean mStopped = false;
	
	/**
	 * Synchronizes access to mMethod to prevent an unlikely race condition
	 * when stopDownload() is called before mMethod has been committed.
	 */
	private Object lock = new Object();

	private boolean messageRemaining=false;

	private ArrayList<OverlayItem> liste;

	

	public StoppableDownloadThread(String url, MapActivityHandler handler,Context context)
	{
		mURL = url;
		mHandler = handler;
		c=context;
	}

	public void run()
	{
		
		String data="";
		try {
			data = HttpClient.get(mURL);
			InputSource payload =new InputSource(new StringReader(data));
						
			XmlParser test = new XmlParser();
			liste = test.parse(payload);
			
			if (mStopped == true)
				return;
			
		} catch (ClientProtocolException e) {
			mHandler.sendError(e.toString());
			e.printStackTrace();
		} catch (IOException e) {
			mHandler.sendError(e.toString());
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			mHandler.sendError(e.toString());
			e.printStackTrace();
		} catch (SAXException e) {
			mHandler.sendError(e.toString());
			e.printStackTrace();
		}
		
		
		mHandler.sendPayload(liste);
		
		
		/*	try {
				payload = client.getContent(mURL);
				
				if (mStopped == true)
					return;
				Log.d(TAG, "ready to parse XML" );
				
				XmlParser test = new XmlParser();
				liste = test.parse(payload);
				
				if (mStopped == true)
					return;
				
				if(liste == null)
				{
					mHandler.sendError("request came back empty, try again later");
					return;
				}
				Log.i(TAG, "xml parsed exiting");
				
				sendPayload(liste);
				
			} catch (ClientProtocolException e) {
				mHandler.sendError(e.toString());
			} catch (IOException e) {
				mHandler.sendError(e.toString());
			} catch (ParserConfigurationException e) {
				mHandler.sendError(e.toString());
			} catch (SAXException e) {
				mHandler.sendError(e.toString());
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				mHandler.sendError(e.toString());
			}
			*/
		}

	/**
	 * This method is to be called from a separate thread.  That is, not the
	 * one executing run().  When it exits, the download thread should be on
	 * its way out (failing a connect or read call and cleaning up).
	 */
	public void stopDownload()
	{
		Log.i(TAG, "download asked to be stoped ofr URL " + mURL);
		
		/* As we've written this method, calling it from multiple threads would
		 * be problematic. */
		if (mStopped == true)
			return;

		/* Too late! */
		if (isAlive() == false)
			return;

		Log.d(TAG, "Stopping download...");

		/* Flag to instruct the downloading thread to halt at the next
		 * opportunity. */
		mStopped = true;

		/* Interrupt the blocking thread.  This won't break out of a blocking
		 * I/O request, but will break out of a wait or sleep call.  While in
		 * this case we know that no such condition is possible, it is always a
		 * good idea to include an interrupt to avoid assumptions about the
		 * thread in question. */
		interrupt();

		/* A synchronized lock is necessary to avoid catching mMethod in
		 * an uncommitted state from the download thread. */
		//synchronized(lock) {
			/* This closes the socket handling our blocking I/O, which will
			 * interrupt the request immediately.  This is not the same as
			 * closing the InputStream yieled by HttpEntity#getContent, as the
			 * stream is synchronized in such a way that would starve our main
			 * thread. */
	/*		if (mMethod != null)
				mMethod.abort();
		}*/

		mHandler.sendAborted();

		Log.i(TAG, "Download stopped.");
	}

	/*public void setHandler(MapActivityHandler handler_) {
		mHandler = handler_;
		
		if(handler_ !=null)
		{	// we got a valid handler, maybe there is still a message to be sent
			Log.i(TAG,"DownloadThread : a new handler is ready ");
			
			sendRemainingMessage();
		}
		else
		{
			Log.i(TAG,"DownloadThread : we cleared the handler");
			
		}
	}*/

	/*private void sendRemainingMessage() {
		
		if(messageRemaining == true)
		{	
			Log.i(TAG,"DownloadThread : Message remaining :" + ((Integer)liste.size()).toString() + "stations");
			messageRemaining = false;
			mHandler.sendPayload(liste);
		}
	}
	
	private void sendPayload (ArrayList<stationItem> liste)
	{
		if(mHandler != null){
			
			Log.i(TAG,"DownloadThread : the message handler is gone, waiting for a new one :" + ((Integer)liste.size()).toString() + "stations");
			
			mHandler.sendPayload(liste);
		}
		messageRemaining = true;
	}*/
}
